// vars/sshNodeJSDeploy.groovy

def call(body) {
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config

    body()

    properties([parameters([choice(choices: ['develop', 'publish'], description: '构建环境', name: 'PROFILE')])])

    assert(config.APP_NAME)

    /* 构建环境 */
    def PFILE = params.PROFILE
    def APP_NAME = config.APP_NAME
    def CICD_APP = config.APP_NAME
    def CICD_REG = "registry.cn-hangzhou.aliyuncs.com/cdw"        
    def CICD_IMAGE = CICD_REG + "/" +CICD_APP
    def CICD_BRANCH = env.BRANCH_NAME

    if(CICD_BRANCH!='master'){
        CICD_NAMESPACE = config.NAMESPACE + '-' + CICD_BRANCH
    }else{
        CICD_NAMESPACE = config.NAMESPACE
    }
    
    if(config.NPM_VERBOSE!=null){
        NPM_VERBOSE = "-verbose"
    }else{
        NPM_VERBOSE = ''
    }
    
    stage('Checkout') {
      checkout scm      
    }
    

    if (env.BRANCH_NAME != 'master') {
        build_tag = "${env.BRANCH_NAME}-${env.BUILD_NUMBER}"
    }else{
        build_tag = "${env.BUILD_NUMBER}"
    }

    stage('Build') {
        sh """
            echo 'npm config'
            npm config set registry http://registry.npm.taobao.org/
            npm config set sass-binary-site http://npm.taobao.org/mirrors/node-sass
            npm config get registry
            npm config get prefix
            npm config get cache
            
            rm -rf dist
            npm install ${NPM_VERBOSE}
            echo 'npm install success'
            npm run build:${PFILE}
            echo 'npm run build success'
            rm -rf ops/dist
            mv dist ops
        """
    }
   
    stage('Image') {
        echo "Build Docker Image Stage"
        dir('./ops'){
            def image = docker.build("${CICD_IMAGE}:${build_tag}")

            docker.withRegistry("http://${CICD_REG}", 'aliyuncs-cdw') {
                image.push("${build_tag}")
                image.push("latest")
            }
        }
    }

    stage('Deploy') {
        echo "Deploy Stage"
        dir('./ops'){      
            sh 'env'            
            sh "sed -i 's/<BUILD_TAG>/${build_tag}/' deployment.yaml" 
            sh "sed -i 's/<BRANCH>/${CICD_BRANCH}/'  deployment.yaml"
            sh "sed -i 's/<NAMESPACE>/${CICD_NAMESPACE}/'  deployment.yaml"  
            
            sh "kubectl apply -f deployment.yaml --namespace=${CICD_NAMESPACE} --record"
            sh "rm -rf dist"
        }
    }
}